package com.game.load
{
	import com.game.gamePort.ILoadNode;
	import com.game.ui.systemBoard.InformationManager;
	
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.utils.Dictionary;
	import flash.utils.getTimer;
	
	public class LoadStateMachine extends EventDispatcher
	{
		private var _stateDic : Dictionary;
		private var _preloadSet : Array;
		private var _isRunning : Boolean;
		private var _startTime : int;
		private var _currNode : ILoadNode;
		
		private static var _instance : LoadStateMachine;
		public static function getInstance():LoadStateMachine
		{
			if(_instance == null)
				_instance = new LoadStateMachine();
			return _instance;
		}
		
		public function LoadStateMachine(target:IEventDispatcher=null)
		{
			super(target);
			init();
		}
		
		private function init():void
		{
			_isRunning = false;
			_preloadSet = [];
			_stateDic = new Dictionary();
			_stateDic[LoadState.LOAD_STATE_BASE_RESOURCE] = new LoadBaseResource();
			_stateDic[LoadState.LOAD_STATE_MAIN_UI] = new LoadUiResource();
			_stateDic[LoadState.LOAD_STATE_CONFIG] = new LoadConfigResource();
		}
		
		public function pushState(vStr : String):void
		{
			var loadNode : ILoadNode = _stateDic[vStr];
			if(loadNode)
			{
				if(_preloadSet.indexOf(loadNode) == -1)
				{
					_preloadSet.push(loadNode);
				}else
				{
					throw new Error("加载节点已存在！");
				}
			}else
			{
				throw new Error("试图访问不存在的加载节点！");
			}
		}
		
		public function run():void
		{
			if(_isRunning)
			{
				throw new Error("加载状态机已经运行");
			}else	
			{
				if(_preloadSet.length > 0)
				{
					_isRunning = true;
					nextNode();
				}else
				{
					throw new Error("没有可运行的节点");
				}
			}
		}
		
		private function nextNode():void
		{ 
			var loadNode : ILoadNode = _preloadSet.shift();
			if(loadNode)
			{
				_currNode = loadNode;
				loadNode.setCompleteNotify(onCompleteNotify);
				loadNode.startLoad();
				_startTime = getTimer();
				trace("----------预加载--" + loadNode.getState() + "--START----------");
			}
			else
			{
				throw new Error("预加载节点异常！");
			}
		}
		
		private function onCompleteNotify():void
		{
			if(_currNode)
			{
				trace("----------预加载--" + _currNode.getState() + "--END----------");
				var index : int = _preloadSet.indexOf(_currNode);
				if(index != -1)
					_preloadSet.splice(index , 1);
				trace("----------耗时--" + (getTimer() - _startTime) + "--MS----------");
				if(_preloadSet.length > 0)
				{
					nextNode();
				}
				else
				{
					free();
					InformationManager.addErrorInfo("这是一个显示信息1");
					InformationManager.addErrorInfo("这是一个显示信息2");
				}
			}
		}
		
		private function free():void
		{
			_preloadSet.length = 0;
			_currNode = null;
			_isRunning = false;
		}
		
	}
}